let li1 = [1, 2, 4], li2 = [1, 3, 4]
let list1 = new ListNode()
let num = list1
for (let i = 0; i < li1.length; i++) {
    num.next = new ListNode(li1[i])
    num = num.next
}
console.log(list1.next);
function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}
let l1 = {
    val: 1,
    next: {
        val: 2,
        next: {
            val: 4,
            next: null
        }
    }
}
let l2 = {
    val: 1,
    next: {
        val: 3,
        next: {
            val: 4,
            next: null
        }
    }
}
// var mergeTwoLists = function (list1, list2) {
//     let head = new ListNode()  // {val: 0, next: null}
//     let cur = head

//     while (list1 && list2) {
//         if (list1.val <= list2.val) {
//             cur.next = list1
//             list1 = list1.next
//         } else {
//             cur.next = list2
//             list2 = list2.next
//         }
//         cur = cur.next
//     }

//     // 当某一个链表已经遍历完了
//     if (list1) {
//         cur.next = list1
//     }
//     if (list2) {
//         cur.next = list2
//     }
//     return head.next
// };
// // 辅助函数：遍历链表并打印节点值
// function printList(head) {
//     let current = head;
//     let result = [];
//     while (current) {
//         result.push(current.val);
//         current = current.next;
//     }
//     console.log(result.join(' -> '));
// }
// let mergedList = mergeTwoLists(l1, l2);
// printList(mergedList);



var mergeTwoLists = function (list1, list2) {
    if (!list1 && !list2) {
        return null
    }
    if (list1 && !list2) {
        return list1
    }
    if (!list1 && list2) {
        return list2
    }
    const head = new ListNode(0)
    let pre = head
    while (list1 && list2) {
        if (list1.val === list2.val) {
            let cur1 = list1.next
            let cur2 = list2.next
            pre.next = list1
            list1.next = list2
            pre = list2
            list1 = cur1
            list2 = cur2
        }
        else if (list1.val < list2.val) {
            let cur1 = list1.next
            pre.next = list1
            pre = list1
            list1 = cur1
        }
        else if (list1.val > list2.val) {
            let cur2 = list2.next
            pre.next = list2
            pre = list2
            list2 = cur2
        }
    }
    if (list1) {
        pre.next = list1
    }
    if (list2) {
        pre.next = list2
    }
    return head.next
};
console.log(mergeTwoLists(l1, l2));
